﻿using B.S.Packaged.Domain;
using B.S.Packaged.ErrorCode;
using B.S.Packaged.WebAPI.Write.Applications.Commands.PackagingPlanCommands;
using MediatR;
using SqlSugar;

namespace B.S.Packaged.WebAPI.Write.Applications.CommandHandlers.PackagingPlanCommandHandlers
{
    public class DelPackagingPlanCommandHandlers : IRequestHandler<DelPackagingPlanCommands, APIResult<object>>
    {
        private readonly ISqlSugarClient db;

        public DelPackagingPlanCommandHandlers(ISqlSugarClient db)
        {
            this.db = db;
        }

        public async Task<APIResult<object>> Handle(DelPackagingPlanCommands request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.code = APIResultCode.success;
            result.msg = "删除成功";
            var ids = request.PackagingPlanIds.Split(',').Select(int.Parse).ToList();

            // 一次性查询所有要删除的计划记录
            var itemsToDelete = await db.Queryable<PackagingPlan>().Where(p => ids.Contains(p.PackagingPlanId)).ToListAsync();


            await db.Deleteable(itemsToDelete).ExecuteCommandAsync();

            // 一次性查询所有要删除的计划明细记录
            var iToDelete = await db.Queryable<PackagingPlanDetails>().Where(p => ids.Contains(p.PackagingPlanId)).ToListAsync();

            await db.Deleteable(iToDelete).ExecuteCommandAsync();

            RecordsOperations records = new RecordsOperations();
            records.Operator = "王浩然";
            records.OperatingTime = DateTime.Now;
            records.OperationContent = "删除计划";

            await db.Insertable(records).ExecuteCommandAsync();

            return result;
        }
    }
}
